package com.opgea.crm.web.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.opgea.crm.common.SetupsAttributeQualifier;
import com.opgea.crm.common.SetupsModuleQualifier;
import com.opgea.crm.common.util.DateUtil;
import com.opgea.crm.common.vo.LeadVo;
import com.opgea.crm.common.vo.MemberVo;
import com.opgea.crm.common.vo.ProjectDetailsVo;
import com.opgea.crm.common.vo.ProjectReportVo;
import com.opgea.crm.domain.entities.Employee;
import com.opgea.crm.domain.entities.Lead;
import com.opgea.crm.domain.entities.ProjectDetails;
import com.opgea.crm.domain.entities.ProjectEstimationHistory;
import com.opgea.crm.domain.entities.SetupsValue;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.domain.modal.QualifierModel;
import com.opgea.crm.services.ActivityService;
import com.opgea.crm.services.AdditionalContactService;
import com.opgea.crm.services.CustomerService;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.LeadService;
import com.opgea.crm.services.ProjectDetailsService;
import com.opgea.crm.services.ProjectEstimationService;
import com.opgea.crm.services.QualifierService;
import com.opgea.crm.services.SetupService;
import com.opgea.crm.web.form.ProjectDetailEstimationForm;
import com.opgea.crm.web.form.ProjectDetailsForm;
import com.opgea.crm.web.form.ProjectReportForm;
import com.opgea.crm.web.form.UserPersonalInfoForm;
import com.opgea.crm.web.modal.LoggedUser;


@Controller
@RequestMapping(value ="project")
public class ProjectController {
	
	Logger logger=Logger.getLogger(ProjectController.class);
	
	@Autowired
	SetupService setupService;
	@Autowired
	ActivityService activityService;
	@Autowired
	ProjectDetailsService projectDetailsService;
	@Autowired
	ProjectEstimationService projectEstiationService;
	@Autowired
	LeadService leadService;
	@Autowired
	EmployeeService employeeService;
	@Autowired
	QualifierService qualifierService;
	@Autowired
	AdditionalContactService additionalContactService;
	
	@Autowired
	CustomerService customerService;

	
	@RequestMapping(method=RequestMethod.GET)
	public String show(HttpServletRequest request)
	{
		return "project";
	}
	
	@RequestMapping(value= "save", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> save(@RequestBody ProjectDetailsForm form,
			                 @RequestParam(required=true, value="action")String action,
			                 HttpServletRequest request)
	{
		ProjectDetails projectDetails = new ProjectDetails();
		if(action.equalsIgnoreCase("update"))
    	{
			projectDetails = projectDetailsService.find(form.getProjectId());
    		
    	}
		
		projectDetails.setProjectName(form.getProjectName());
		projectDetails.setProjectDetails(form.getProjectDetails().getBytes());
		projectDetails.setStatus(setupService.findById(form.getStatusId()));
		projectDetails.setPriority(setupService.findById(form.getPriorityId()));
		
		projectDetails.setCustomer(customerService.find(form.getLeadId()));
		projectDetails.setContactTo(additionalContactService.find(new Long(form.getContactToId())));
        
		projectDetails.setActualStartDate(DateUtil.stringToDate(form.getActualStartDate()));
		projectDetails.setActualEndDate(DateUtil.stringToDate(form.getActualEndDate()));
		projectDetails.setActualBudget(Double.parseDouble(form.getActualBudget()));
		projectDetails.setActualTakenHrs(Integer.parseInt(form.getActualHrs()));
		
		if(action.equalsIgnoreCase("save"))
		{
			projectDetails.setCreatedBy(LoggedUser.getUser(request));
			projectDetails.setCreatedAt(new Date());
			projectDetailsService.create(projectDetails);
		}
		if(action.equalsIgnoreCase("update"))
		{
			projectDetailsService.update(projectDetails);
		}
		
    	return JsonModelMap.success().data(projectDetails.getId());	
    }
	
	
	
	@RequestMapping(method =RequestMethod.GET, value="assignMemberToProject")
	public @ResponseBody
	Map<String, Object>assignMemberToProject(@RequestParam("userId") String userId){
		Employee emp = employeeService.find(new Long(userId));
		  return JsonModelMap.success().data(new UserPersonalInfoForm(emp));
	}
	
	@RequestMapping(value= "saveEstimationInfo", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> saveEstimationInfo(@RequestBody ProjectDetailEstimationForm form,
										   HttpServletRequest request)
	{

		ProjectDetails projectDetails = projectDetailsService.find(3751l);
		ProjectEstimationHistory estimation = new ProjectEstimationHistory();
		
		System.out.println("PrjectDetailEstimationForm : "+form);

		estimation.setEstimatedStartDate(DateUtil.stringToDate(form.getEstStartDate()));
		estimation.setEstimatedEndDate(DateUtil.stringToDate(form.getEstEndDate()));
		estimation.setEstimatedProjectBudget(new Double(form.getEstBudget()));
		estimation.setEstimatedProjectHrs(new Integer(form.getEstHrs()));
		estimation.setBudgetVariation(new Float(form.getBudgetDiff()));
		estimation.setHrsVariation(new Float(form.getHrsDiff()));
		estimation.setProject(projectDetails);
		
		projectEstiationService.create(estimation);
        System.out.println("after save");
        
        return JsonModelMap.success().data(estimation.getId());
    }
	
	 @RequestMapping(value ="/projectReqCombo" )
		public @ResponseBody
		Map<String ,Object> issueCombo(@RequestParam(value ="operation") String operation,HttpServletResponse response)
		{
			List<SetupsValue> result = null;
			if(operation.equalsIgnoreCase("statusTypes"))
				result  = setupService.listSetupValue(SetupsModuleQualifier.Project.ordinal(),SetupsAttributeQualifier.Status.ordinal());
			if(operation.equalsIgnoreCase("priorityTypes"))
				result = setupService.listSetupValue(SetupsModuleQualifier.Project.ordinal(), SetupsAttributeQualifier.Priority.ordinal());
			return JsonModelMap.success().data(result);
		}
	
		
	@RequestMapping(method=RequestMethod.GET, value="showMemberList")
	public @ResponseBody 
	Map<String, Object> showMemberList(@RequestParam(required=false, value="criteria") String criteria,
			                           @RequestParam(required=false) Long projectId)
	{
		logger.debug("ProjectController >> showMemberList");
		if(criteria == null && projectId == null){
			return JsonModelMap.success();
		}
		else{
			List<MemberVo> project = projectDetailsService.findMemberList(criteria,projectId);
			return JsonModelMap.success().data(project);
		}
	}
	
	@RequestMapping(method =RequestMethod.GET, value= "memberTypeList")
	public @ResponseBody
	Map<String, Object>  memberTypeList()
	{
		logger.debug("ProjectController >> memberTypeList");
		return JsonModelMap.success().data(qualifierService.getEmployeeTypes());
	}
	
	@RequestMapping(method =RequestMethod.GET, value= "memberListByProjectId")
	public @ResponseBody
	Map<String, Object>  memberListByProjectId(@RequestParam(required = false) String memberProjectId)
	{
		logger.debug("ProjectController >> memberList");
		List<MemberVo> members = null;
		if(memberProjectId == null){
			members = new ArrayList<MemberVo>();
		}else{
			members = projectDetailsService.findMemberByProjectId(new Long(memberProjectId));	
		}
		 
      return JsonModelMap.success().data(members);
		
	}
	
	
	@RequestMapping(method = RequestMethod.GET, value ="findContactName")
	public @ResponseBody
	Map<String, Object> findContactName(@RequestParam(required=true, value="leadId") String leadId)
	{
		  System.out.println("Associated Id of company");
		  List<QualifierModel> empList = null;
		  Lead customer = new Lead();
		  if(leadId!=null){
		    customer = leadService.findLead(new Long(leadId));
		  	empList = additionalContactService.findAllContactNameByLeadId(new Long(leadId));
		  }
		 
		  return JsonModelMap.success().data(empList);
	}
	
	@RequestMapping(method = RequestMethod.GET, value="showProjectDetails") 
	public @ResponseBody
	Map<String, Object> showProjectDetails(@RequestParam(required=false,value="projectId") String projectId)
	{
		logger.debug("in show project details");
		if(projectId == null){
			return JsonModelMap.success();
		}
		else{
			ProjectDetails projectDetails = projectDetailsService.find(new Long(projectId));
			return JsonModelMap.success().data(new ProjectDetailsForm(projectDetails));
		}
	}
	

	@RequestMapping(method = RequestMethod.POST, value ="addMember")
	public @ResponseBody
	Map<String, Object> addMember(@RequestParam("projectId")Long projectId,
			                      @RequestParam("empId")String empId)
	{
		String[] userIds = empId.split(",");
		
		ProjectDetails project = projectDetailsService.find(projectId);
		
		List<Employee> members =  project.getMembers();
				
		Employee member = null;
		for(String id : userIds){	
			member = employeeService.find(new Long(id));
			members.add(member);
		}
		project.setMembers(members);
		projectDetailsService.update(project);
		Map<String, Object> successMap = new HashMap<String, Object>();
		successMap.put("success", "A Project Details added successfully!");

    	return successMap;	
	}
	
	@RequestMapping(method=RequestMethod.GET ,value="showProjectList")
	public @ResponseBody
	Map<String, Object> showProjectList(
			@RequestParam(required=false, value="criteria") String criteria,
			@RequestParam(required=false, value="value")String value){
		
		logger.debug("ProjectSearchController >> showProjectDetails");
		if(criteria== null && value == null){
			return JsonModelMap.success();
		}
		else{
			List<ProjectDetailsVo> projects = projectDetailsService.findProjectList(criteria, value);
			return JsonModelMap.success().data(projects);
		}
	}
	
	@RequestMapping(method=RequestMethod.GET, value="projectSearchTypes")
    public @ResponseBody Map<String, Object> projectSearchTypes(){
 	   return JsonModelMap.success().data(projectDetailsService.getProjectSearchCriteriaTypes());
    }
	
	@RequestMapping(method = RequestMethod.GET, value = "customerSearchCriteria")
	public @ResponseBody
	Map<String, Object> customerSearchCriteria(){
		return JsonModelMap.success().data(leadService.getLeadSearchCriteriaTypes());
	}
	
	
	@RequestMapping(value="showCustomer",method=RequestMethod.GET)
	public @ResponseBody
	Map<String,Object> showCustomer(@RequestParam(required=false) String criteria,
								    @RequestParam(required=false) String value)
	{
		logger.debug("SearchCustomer >> showCustomer");
		if(criteria == null && value == null){
			return JsonModelMap.success();
		}
		else{
			List<LeadVo> list = customerService.findDynamically(criteria, value);
			return JsonModelMap.success().data(list);
		}
	}
	
	@RequestMapping(method = RequestMethod.POST, value="deleteMemberDetail")
	public @ResponseBody
	Map<String, Object> deleteMemberDetail(@RequestParam("memberId")Long memberId,
			                               @RequestParam("projectId")Long projectId)
	{
		Employee member = employeeService.find(memberId);
		ProjectDetails proDetails = projectDetailsService.find(projectId);
		List<Employee> memberList = proDetails.getMembers();
		memberList.remove(member);
		proDetails.setMembers(memberList);
		projectDetailsService.update(proDetails);
		return JsonModelMap.successWithMessage("success");
	}
	
	@RequestMapping(method = RequestMethod.GET, value="showProjectReport")
	public @ResponseBody
	Map<String, Object> showProjectReport(@RequestParam("projectId") String projectId)
	{
		logger.debug("ProjectController >> showProjectReport");
		ProjectDetails projectDetails = projectDetailsService.find(new Long(projectId));
		return JsonModelMap.success().data(new ProjectReportForm(projectDetails));
	   
	}
	
	@RequestMapping(method =RequestMethod.GET, value= "memberReportListByProjectId")
	public @ResponseBody
	Map<String, Object>  memberReportListByProjectId(@RequestParam(required = false) Long memberProjectId)
	{
		System.out.println("ProjectController >> memberReportList");
		List<ProjectReportVo> members=null;
		if(memberProjectId!=null)
		 members = projectDetailsService.findMemberReportList(memberProjectId);
        return JsonModelMap.success().data(members);
		
	}

}
